package chatmodels;

import java.util.Observer;
import event.ObservableEvent;
import interfaces.ChatModel;
import java.io.IOException;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;



public class RabbitMQModel implements ChatModel {

	private String message = new String();
	private ObservableEvent messageReceived = new ObservableEvent();
	private static final String EXCHANGE_NAME = "chat";

	@Override
	public void addInputReceivedListener(Observer observer) {
		this.messageReceived.addObserver(observer);

	}

	@Override
	public String getMessage() {
		String message = this.message;
		this.message = "";
		return message;
	}

	@Override
	public void sendMessage(String message) {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("109.75.176.134");
		Connection connection = null;
		Channel channel = null;
		try {
			connection = factory.newConnection();
			channel = connection.createChannel();
			channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
			channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
			channel.close();
			connection.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public void waitForMessages() {
		new Thread(new Runnable() {
			public void run() {
				ConnectionFactory factory = new ConnectionFactory();
				factory.setHost("109.75.176.134");
				Connection connection = null;
				Channel channel = null;
				String queueName = null;
				try {
					connection = factory.newConnection();
					channel = connection.createChannel();
					channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
					queueName = channel.queueDeclare().getQueue();
					channel.queueBind(queueName, EXCHANGE_NAME, "");
					QueueingConsumer consumer = new QueueingConsumer(channel);
					channel.basicConsume(queueName, true, consumer);

					while (true) {
						QueueingConsumer.Delivery delivery = consumer
								.nextDelivery();
						message = new String(delivery.getBody());

						messageReceived.notifyEvent();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ShutdownSignalException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ConsumerCancelledException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}).start();

	}

}
